<template>
  <yt-page title="修改密码" theme="white">
    <yt-form :model="form" :rules="rules" class="form" :full="false">
      <div class="box">
        <yt-input class="input" v-model="form.password" type="password" placeholder="请输入原始密码" align="left" border></yt-input>
      </div>
      <div class="box">
        <yt-input class="input" v-model="form.newPassword" type="password" placeholder="请输入新密码" align="left" border></yt-input>
      </div>
      <div class="box">
        <yt-input class="input" v-model="form.confirmPassword" type="password" placeholder="请输入确定密码" align="left" border></yt-input>
      </div>
      <yt-btn class="btn" theme="black" validator :loading="doConfirm">确定</yt-btn>
    </yt-form>
  </yt-page>
</template>

<script >
import { GetStore, Store } from '@/store'
import { commonApi } from '@/common/api/commonApi.js'

export default {
  name: 'modifyPwd',
  data() {
    return {
      form: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        password: { type: 'string', required: true, message: '原始密码不能为空!' },
        newPassword: { type: 'string', required: true, message: '新密码不能为空!' },
        confirmPassword: [
          { type: 'string', required: true, message: '确定密码不能为空!' },
          {
            validator: (rule, value, callback) => {
              if (this.form.newPassword === this.form.confirmPassword) {
                callback()
              } else {
                callback(new Error('两次密码不一致，请重新输入'))
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    async doConfirm(loaded) {
      try {
        let user = await commonApi.login({ username: GetStore(Store.user).username, password: this.form.password })
        user.setPassword(this.form.newPassword)
        await user.save()
        this.$Toast('修改密码成功！')
        this.$router.$back()
      } catch (e) {
        this.$Toast('修改密码失败！', 'error')
      }
      loaded()
    }
  }
}
</script>

<style scoped lang="stylus" type="text/stylus" rel="stylesheet/stylus">
.form {
  padding: 10px 20px 0;
  background-color: #ffffff;
}

.box {
  margin: 0 10px;
}

.input {
  height: 32px;
  margin: 15px 0;
}

.btn {
  margin-top: 40px;
}
</style>
